import { NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'

// GET - 获取健康数据
export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url)
    const userId = searchParams.get('userId')
    const dataType = searchParams.get('dataType')
    const startDate = searchParams.get('startDate')
    const endDate = searchParams.get('endDate')
    const limit = parseInt(searchParams.get('limit') || '1000')

    console.log('健康数据API请求参数:', {
      userId,
      dataType,
      startDate,
      endDate,
      limit
    })

    // 构建查询条件
    const where: any = {
      deleted_at: 0 // 只查询未删除的记录
    }
    
    if (userId) {
      where.user_id = parseInt(userId)
    }
    
    if (dataType) {
      // 根据dataType映射到对应的type值
      switch (dataType) {
        case 'heart_rate':
          where.type = 'heart_rate'
          break
        case 'sleep':
          where.type = 'sleep'
          break
        default:
          where.type = dataType
      }
    }

    // 时间范围查询
    if (startDate && endDate) {
      const startTimestamp = new Date(startDate).getTime()
      const endTimestamp = new Date(endDate).getTime()
      
      console.log('时间戳比较:', {
        startDate,
        endDate,
        startTimestamp,
        endTimestamp,
        startDateFormatted: new Date(startTimestamp).toISOString(),
        endDateFormatted: new Date(endTimestamp).toISOString()
      })
      
      where.timestamp = {
        gte: BigInt(startTimestamp),
        lt: BigInt(endTimestamp) // 使用 lt 而不是 lte，确保不包含结束时间
      }
    }

    console.log('查询条件:', where)

    // 查询健康记录
    const healthRecords = await prisma.yh_logs.findMany({
      where,
      include: {
        user: {
          select: {
            id: true,
            name: true,
            mobile: true
          }
        }
      },
      orderBy: {
        timestamp: 'desc'
      },
      take: limit
    })

    // 转换BigInt为普通数字以便JSON序列化
    const serializedRecords = healthRecords.map(record => ({
      ...record,
      timestamp: Number(record.timestamp) // 将BigInt转换为number
    }))

    console.log('查询结果:', {
      recordsCount: serializedRecords.length,
      firstRecord: serializedRecords[0] ? {
        id: serializedRecords[0].id,
        type: serializedRecords[0].type,
        timestamp: serializedRecords[0].timestamp,
        hasData: !!serializedRecords[0].data
      } : null
    })

    return NextResponse.json({
      success: true,
      data: {
        logs: serializedRecords
      },
      total: serializedRecords.length
    })

  } catch (error) {
    console.error('获取健康数据失败:', error)
    return NextResponse.json(
      { 
        success: false, 
        error: '获取健康数据失败',
        message: error instanceof Error ? error.message : '未知错误'
      },
      { status: 500 }
    )
  }
}

// POST - 创建健康记录
export async function POST(request: Request) {
  try {
    const body = await request.json()
    const { userId, type, data, deviceId } = body

    // 验证必填字段
    if (!userId || !type || !data) {
      return NextResponse.json(
        { success: false, error: '缺少必填字段' },
        { status: 400 }
      )
    }

    const currentTime = Math.floor(Date.now() / 1000)

    // 创建健康记录
    const healthRecord = await prisma.yh_logs.create({
      data: {
        user_id: parseInt(userId),
        type,
        device_id: deviceId || '',
        data: typeof data === 'string' ? data : JSON.stringify(data),
        timestamp: BigInt(Date.now()),
        created_at: currentTime,
        updated_at: currentTime
      },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            mobile: true
          }
        }
      }
    })

    return NextResponse.json({
      success: true,
      data: healthRecord,
      message: '健康记录创建成功'
    })

  } catch (error) {
    console.error('创建健康记录失败:', error)
    return NextResponse.json(
      { 
        success: false, 
        error: '创建健康记录失败',
        message: error instanceof Error ? error.message : '未知错误'
      },
      { status: 500 }
    )
  }
}